package middleware

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"strings"
	"test/common"
	"test/model"
)

func UserMiddleware() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		//获得authorization header
		tokenString := ctx.GetHeader("Authorization")

		//验证token
		if tokenString == "" || !strings.HasPrefix(tokenString,"Bearer") {
			ctx.JSON(http.StatusUnauthorized,gin.H{"code":401,"msg":"权限不足"})
			ctx.Abort()
			return
		}
		tokenString = tokenString[7:]
	token, claims, err := common.ParseToken(tokenString)
	if err != nil || !token.Valid {
		ctx.JSON(http.StatusUnauthorized, gin.H{"code":401,"msg":"权限不足"})
		ctx.Abort()
		return
	}

	//验证完成后获取claim中的userID
	userId := claims.UserId
	DB := common.GetDB()
	var student model.Students
	DB.First(&student,userId)

	//用户不存在

	//if student.Sname {
	//	ctx.JSON(http.StatusUnauthorized, gin.H{"code":401,"msg":"权限不足"})
	//	ctx.Abort()
	//	return
	//}

	//用户存在 将user信息写入上下文
	ctx.Set("Student",student)
	ctx.Next()
	}
}
